//
//  LoginService.swift
//  ezyform
//
//  Created by FengMoennig on 12/28/15.
//  Copyright © 2015 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import MBProgressHUD
import HandyJSON
import SDWebImage
class LoginService: BaseService {
    
    func login(_ model: LoginInfoModel){
        
        // validate presense of required parameters
        if model.email.count > 0 &&
            model.password.count > 0 {
            if APPConfig.loginInfo.email != "" && !(APPConfig.loginInfo.email as NSString).isEqual(to: model.email) {
                UserDefaults.standard.set("" as String, forKey: APPConfig.LoginUserEmailKey)
                UserDefaults.standard.set("" as String, forKey: APPConfig.LoginUserTokenKey)
                UserDefaults.standard.set("" as String, forKey: APPConfig.LoginUserFullNameKey)
                
            }
            
            //Set User Info
            APPConfig.loginInfo.email = model.email.lowercased()
            APPConfig.loginInfo.password = model.password
            
            UserDefaults.standard.set(model.email, forKey: APPConfig.LoginUserEmailKey)
            let alRequest = ALRequest.init(mainURL: APIConfig.getRequestAPIForV2(APIConfig.LoginAPI), method: .post, headers: RequestConstant.AuthLoginOtherParam, paramDict: RequestConstant.AuthLoginParam, successBlock: {(result,_) -> Void in
                let dic :NSDictionary = result as! NSDictionary
                let acceccToken = dic.object(forKey: "access_token") as? String ?? ""
                let fullName = dic.object(forKey: "full_name") as? String ?? ""
                self.configAccessToken(model.password,acceccToken,fullName)
                
                self.returnBlock(acceccToken as AnyObject, nil)
            }) { (code, error) -> Void in
                self.errorBlock(code,error)
            }
            
            alRequest.startRequest()
        }else{
            self.errorBlock!("","Email or password is missing")
        }
    }
    fileprivate func configAccessToken(_ pwd: String, _ token: String,_ fullName: String) {
        APPConfig.loginInfo.password = pwd
        APPConfig.loginInfo.access_token = token
        APPConfig.loginInfo.fullName = fullName
        
        UserDefaults.standard.set(token, forKey: APPConfig.LoginUserTokenKey)
        UserDefaults.standard.set(fullName, forKey: APPConfig.LoginUserFullNameKey)
        UserDefaults.standard.set(pwd, forKey: APPConfig.CachePasswordKey)
        //standard view
        if let data = UserDefaults.standard.object(forKey: APPConfig.MagnifiedViewKey) as? Bool, data{
            Constant.standardViewFlag = false
        }else{
            Constant.standardViewFlag = true
        }
    }
    //用户登录信息有SAMKeychain修改为UserDefaults，当App卸载后登录账号信息一同删掉
    class func initAuthorityFromKeychain(){
        //UserDefaults Email
        if let email = UserDefaults.standard.object(forKey: APPConfig.LoginUserEmailKey) as? String  {
            APPConfig.loginInfo.email = email.lowercased()
            
            //Token
            if let token = UserDefaults.standard.object(forKey: APPConfig.LoginUserTokenKey) as? String  {
                APPConfig.loginInfo.access_token = token
                
            }
            //Full name
            if let fullName = UserDefaults.standard.object(forKey: APPConfig.LoginUserFullNameKey) as? String  {
                APPConfig.loginInfo.fullName = fullName
                
            }
            //Accredited Number
            if let data = UserDefaults.standard.object(forKey: email + "-AccreditedNumber") as? String  {
                APPConfig.loginInfo.accreditedNumber = data
            }
            
            //Accredited Number
            if let data = UserDefaults.standard.object(forKey: email + "-SaaNumber") as? String  {
                APPConfig.loginInfo.saaNumber = data
            }
            
            //Accredited Number
            if let data = UserDefaults.standard.object(forKey: email + "-PlumberLicenses") as? String  {
                APPConfig.loginInfo.plumber_licenses = data
            }
            //avatar
            if let data = UserDefaults.standard.object(forKey: APPConfig.LoginUserAvatarKey) as? String  {
                APPConfig.loginInfo.avatarURLStr = data
            }
            //处理老的缓存密码,将老key替换为新的key
            if let data = UserDefaults.standard.object(forKey: APPConfig.OldCachePasswordKey) as? String, data != ""{//处理老密码
                UserDefaults.standard.set(data, forKey: APPConfig.CachePasswordKey)
                UserDefaults.standard.removeObject(forKey: APPConfig.OldCachePasswordKey)//删除key
            }
            //统一从新key入口
            if let data = UserDefaults.standard.object(forKey: APPConfig.CachePasswordKey) as? String, data != ""{//处理老密码
                APPConfig.loginInfo.password = data
            }else {//没有缓存密码直接清空token,让用户直接重新登录，让用户可以使用Login more options功能
                APPConfig.loginInfo.access_token = ""
                UserDefaults.standard.set(nil, forKey: APPConfig.LoginUserTokenKey)
            }
            //standard view
            if let data = UserDefaults.standard.object(forKey: APPConfig.MagnifiedViewKey) as? Bool, data{
                Constant.standardViewFlag = false
            }else{
                Constant.standardViewFlag = true
            }
            //
            UserDefaults.standard.synchronize()
        }
    }
    
    class func logOut(){
        //logout要清空fcm token
        let service = NotificationService()
        service.setBlockAfterNetwork { (result,_) in
            
        } errorBlock: {(code,msg) in
            
        }
        service.setFireBaseToken(true)
        
//        SDImageCache.shared().clearMemory()//清除头像的内存缓存
        self.toLoginVC()
        
    }
    class func toLoginVC(_ toLoginMethodFlag: Bool = false){
        guard let window = Tool.getKeyWindow() else {return}
        //clear key chain
        if APPConfig.loginInfo.email != "" {
            Tool().setValueOfUserDefaults("", key: APPConfig.LoginUserTokenKey)
            Tool().setValueOfUserDefaults("", key: APPConfig.LoginUserFullNameKey)
            Tool().setValueOfUserDefaults("", key: APPConfig.LoginUserAvatarKey)
            SDWebImageManager.shared().imageCache?.clearMemory()//清除头像的内存缓存
            APPConfig.loginInfo.avatarURLStr = ""
        }
        let vc = LoginViewController()
        vc.autoToFavoriteLoginMethod = toLoginMethodFlag
        let navVC = BaseNavigationController(rootViewController: vc)
        DispatchQueue.main.async {
            window.rootViewController = navVC
            ReachabilityHelper.shared.showNetworkStatusView()
        }
    }
    //send email for forgetting password
    func forgotPwd(email: String){
        let url : String = APIConfig.getRequestAPIForV2(APIConfig.ForgotPwdAPI)
        
        let params : [String: String] = ["email" : email]
        let alRequest = ALRequest.init(mainURL: url, method: .post, headers: RequestConstant.AuthLoginOtherParam, paramDict: params, successBlock: { (obj,_) -> Void in
            self.returnBlock(obj, nil)
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    //send verification code for delete account
    func sendVerificationCode(){
        let url : String = APIConfig.getRequestAPIForV2(APIConfig.SentVerificationCode)
        
        let alRequest = ALRequest.init(mainURL: url, method: .post, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: { (obj,_) -> Void in
            self.returnBlock(obj, nil)
        }, errorBlock: { (code, obj) -> Void in
            self.errorBlock?(code, obj)
        })
        alRequest.startRequest()
    }
    func deleteAccount(_ verificationCode: String){
        let url : String = APIConfig.getRequestAPIForV2(APIConfig.DeleteAccount)
        
        let params : [String: String] = ["code" : verificationCode]
        let alRequest = ALRequest.init(mainURL: url, method: .post, headers: RequestConstant.AuthTokenParam, paramDict: params, successBlock: { (obj,_) -> Void in
            self.returnBlock(obj, nil)
        }, errorBlock: { (code, obj) -> Void in
            self.errorBlock?(code, obj)
        }) 
        alRequest.startRequest()
    }
    
    func sendConfirmEmail(){
        let alRequest = ALRequest.init(mainURL: APIConfig.getRequestAPIForV2(APIConfig.SendEmailConfirmAPI), method: .post, headers: RequestConstant.AuthLoginOtherParam, paramDict: RequestConstant.AuthLoginParam, successBlock: {(result,_) -> Void in
            self.returnBlock(result,nil)
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        
        alRequest.startRequest()
    }
}
